package com.tianqu.tms.core.webservice;

import java.sql.Timestamp;

import javax.jws.WebService;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.util.ImageUtils;
import com.tianqu.tms.core.util.Registry;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.core.util.enums.WeChatResultCode;
import com.tianqu.tms.dao.CarDao;
import com.tianqu.tms.dao.MemberDao;
import com.tianqu.tms.dao.TmsDao;
import com.tianqu.tms.dao.TransferAcceptedInfoDao;
import com.tianqu.tms.dao.TransferFinanceInfoDao;
import com.tianqu.tms.dao.TransferProcessHistoryDao;
import com.tianqu.tms.dto.MarketCarInfoDto;
import com.tianqu.tms.dto.MemberDto;
import com.tianqu.tms.dto.TransferAcceptedInfoDto;
import com.tianqu.tms.dto.TransferFinanceInfoDto;
import com.tianqu.tms.dto.TransferProcessHistoryDto;
import com.tianqu.tms.entity.Attn;
import com.tianqu.tms.entity.Car;
import com.tianqu.tms.entity.IntegralRegister;
import com.tianqu.tms.entity.Member;
import com.tianqu.tms.entity.TransferAcceptedInfo;
import com.tianqu.tms.entity.User;

/**
 * @author Huang Wei
 *
 */

@WebService(endpointInterface="com.tianqu.tms.core.webservice.TmsCarWeChatService",serviceName="TmsCarWeChatService")
public class TmsCarWeChatServiceImpl extends AbstractTmsCarWeChatService implements TmsCarWeChatService {
	
	private static Logger LOGGER = Logger.getLogger(TmsCarWeChatServiceImpl.class);// log
	
 
	@Override
	public int agencyCarRegister(String serial, String licensePlate, int mileage, String vendorId, String brandId,
			String carStyleId, int color, int memberId, String price, String transferSerial, String sendCardimages,
			String jqx, String yearCarefulPeriod,String imageType) {

		int r = WeChatResultCode.SUCCESS.getValue();
		try {
			StringBuffer log = new StringBuffer();
			log.append("agencyCarRegister execute,");
			log.append(" ,serial :"+serial);
			log.append(" ,licensePlate :"+licensePlate);
			log.append(" ,mileage :"+mileage);
			log.append(" ,vendorId :"+vendorId);
			log.append(" ,brandId :"+brandId);
			log.append(" ,carStyleId :"+carStyleId);
			log.append(" ,color :"+color);
			log.append(" ,memberId :"+memberId);
			log.append(" ,price :"+price);
			log.append(" ,jqx :"+jqx);
			log.append(" ,yearCarefulPeriod :"+yearCarefulPeriod);
			log.append(" ,imageType :"+imageType);
			LOGGER.info(log);
			
			if(StringUtil.isNullOrBlank(serial)){
				r= WeChatResultCode.ERROR_1001.getValue();
			    LOGGER.debug("serial :"+serial +"车辆编号不能为空!");
			    return r;
			}
			if(StringUtil.isNullOrBlank(licensePlate)){
				r= WeChatResultCode.ERROR_1001.getValue();
			    LOGGER.debug("licensePlate :"+licensePlate +"车牌号码不能为空!");
			    return r;
			}
			if(mileage == 0){
				r= WeChatResultCode.ERROR_1001.getValue();
			    LOGGER.debug("mileage :"+mileage +"表显里程不能为空!");
			    return r;
			}
			if(StringUtil.isNullOrBlank(vendorId)){
				r= WeChatResultCode.ERROR_1001.getValue();
			    LOGGER.debug("vendorId :"+vendorId +"品牌id不能为空!");
			    return r;
			}
			if(StringUtil.isNullOrBlank(brandId)){
				r= WeChatResultCode.ERROR_1001.getValue();
			    LOGGER.debug("brandId :"+brandId +"车系id不能为空!");
			    return r;
			}
			if(StringUtil.isNullOrBlank(carStyleId)){
				r= WeChatResultCode.ERROR_1001.getValue();
			    LOGGER.debug("carStyleId :"+carStyleId +"款式id不能为空!");
			    return r;
			}
			if(color == 0){
				r= WeChatResultCode.ERROR_1001.getValue();
			    LOGGER.debug("color :"+color +"颜色不能为空!");
			    return r;
			}
			if(memberId == 0){
				r= WeChatResultCode.ERROR_1001.getValue();
			    LOGGER.debug("memberId :"+memberId +"商户不能为空!");
			    return r;
			}
			if(StringUtil.isNullOrBlank(price)){
				r= WeChatResultCode.ERROR_1001.getValue();
			    LOGGER.debug("price :"+price +"预售价格不能为空!");
			    return r;
			}
			if(!StringUtil.isNullOrBlank(sendCardimages) && StringUtil.isNullOrBlank(imageType)){
				r= WeChatResultCode.ERROR_1001.getValue();
			    LOGGER.debug("sendCardimages :"+sendCardimages +"图片类型不能为空!");
			    return r;
			}
			
			
			//
			Car car = new Car();
			// 处理图片
			if (sendCardimages != null&& !"".equals(sendCardimages)) {
				//
				String imageDir = ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.WECHAT_PIC_URL_KEY)+serial+"."+imageType);
				ImageUtils.generateImage(sendCardimages,imageDir);
				String imageUrl = ImageUtils.getImageUrl(Registry.getConfig(TmsConstants.WECHAT_PIC_URL_KEY)+serial+"."+imageType);
				car.setPhoto_1(imageUrl);
			} else {
				LOGGER.info("serial :"+serial +"行驶证照片为空!");
				car.setPhoto_1("");
			}
			car.setSerial(serial);
			car.setLicensePlate(licensePlate);
			car.setMileage(mileage);
			car.setVendorId(vendorId);
			car.setBrandId(brandId);
			car.setCarStyleId(carStyleId);
			car.setColor(color);
			car.setMemberId(memberId);
			car.setPrice(Integer.parseInt(price));
			car.setJqx(jqx);
			car.setYearCarefulPeriod(yearCarefulPeriod);
			car.setUpdateUserId(1);
			r = agencyCarRegister(car);
			LOGGER.debug("serial :"+serial +"result :"+r);
			
		} catch (Exception e) {
			LOGGER.error("agencyCarRegister error",e);
		}
		return r;
		
	}

 
	@Override
	public int transferApply(String transferSerial, String basicCarId, String licensePlate, int LicensePlateType, String photo,
			String memberId, int memberType, int marketType,String imageType) {
		

		int r = WeChatResultCode.SUCCESS.getValue();
		try {
			StringBuffer log = new StringBuffer();
			log.append("transferApply execute,");
			log.append(" transferSerial :"+transferSerial);
			log.append(" basicCarId :"+basicCarId);
			log.append(" licensePlate :"+licensePlate);
			log.append(" LicensePlateType :"+LicensePlateType);
			log.append(" memberId :"+memberId);
			log.append(" memberType :"+memberType);
			log.append(" marketType :"+marketType);
			log.append(" imageType :"+imageType);
			LOGGER.info(log);
			
			if(StringUtil.isNullOrBlank(transferSerial)){
				r= WeChatResultCode.ERROR_1001.getValue();
			    LOGGER.debug("transferSerial :"+transferSerial +"过户流水号不能为空!");
			    return r;
			}
			if(StringUtil.isNullOrBlank(basicCarId)){
				r= WeChatResultCode.ERROR_1001.getValue();
			    LOGGER.debug("transferSerial :"+transferSerial +"车辆编号不能为空!");
			    return r;
			}
			if(StringUtil.isNullOrBlank(licensePlate)){
				r= WeChatResultCode.ERROR_1001.getValue();
			    LOGGER.debug("transferSerial :"+transferSerial +"车牌号码不能为空!");
			    return r;
			}
			if(StringUtil.isNullOrBlank(memberId)){
				r= WeChatResultCode.ERROR_1001.getValue();
			    LOGGER.debug("transferSerial :"+memberId +"会员ID不能为空!");
			    return r;
			}
			
			if(!StringUtil.isNullOrBlank(photo) && StringUtil.isNullOrBlank(imageType)){
				r= WeChatResultCode.ERROR_1001.getValue();
			    LOGGER.debug("transferSerial :"+transferSerial +"图片类型不能为空!");
			    return r;
			}
			
			//
			TransferAcceptedInfo accept = new TransferAcceptedInfo();
			// 处理图片
			if (photo != null&& !"".equals(photo)) {
				//
				String imageDir = ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.WECHAT_PIC_URL_KEY)+transferSerial+"."+imageType);
				ImageUtils.generateImage(photo,imageDir);
				String imageUrl = ImageUtils.getImageUrl(Registry.getConfig(TmsConstants.WECHAT_PIC_URL_KEY)+transferSerial+"."+imageType);
				accept.setPhoto_1(imageUrl);
			} else {
				LOGGER.info("transferSerial :"+transferSerial +"车辆照片为空!");
				accept.setPhoto_1("");
			}
			//过户流水号
			accept.setSerial(transferSerial);
			//车辆编号
			accept.setBasicCarId(basicCarId);
			//车牌号码
			accept.setLicensePlate(licensePlate);
			//号牌种类
			accept.setCy_cardType(String.valueOf(LicensePlateType));
			//会员ID
			accept.setMemberId(memberId);
			//否是库存车辆
			accept.setMarketType(marketType);
			
			r = transferApply(accept,memberType);
			LOGGER.debug("transferSerial :"+transferSerial +"result :"+r);
			
		} catch (Exception e) {
			LOGGER.error("transferApply error",e);
		}
		return r;
			
	}
	
	@Override
	/**
	 * @param serial 过户流水号
	 * @param basicCarId 车辆编号
	 * @param licensePlate 车牌号码
	 * @param marketType 车辆库存类型
	 * @param carOwner 车主姓名
	 * @param businessType 业务种类
	 * @param licensePlateCol 车牌颜色
	 * @param vin 车架号
	 * @param price 交易价格
	 * @param cyCardType 号牌种类
	 * @param photo1 车辆照片
	 * @param memberId 会员ID
	 * @param attnId 经办人ID
	 * @param materialImages1 资料照片1
	 * @param materialImages2 资料照片2
	 * @param materialImages3 资料照片3
	 * @param materialImages4 资料照片4
	 * @param materialImages5 资料照片5
	 **/
	//workload:3.1.4 add
	//2、【车代办】申请过户
	//返还结果：1、成功但没有缴费；2、失败；3~6成功但是缴费没有成功；7、成功并且缴费也成功
	public int transferDataSyn40000(String serial, String basicCarId, String licensePlate, Integer marketType, String carOwner, Integer businessType, 
			Integer licensePlateCol, String vin,Integer price, Integer cyCardType, String photo1,String memberId,String attnId,String materialImages1, 
			String materialImages2, String materialImages3, String materialImages4, String materialImages5) {
		int r = 7;
		try {
			StringBuffer log = new StringBuffer();
			log.append("TransferServiceImpl.transferDataSyn40000 execute,");
			log.append("[serial=").append(serial);
			log.append(",basicCarId=").append(basicCarId);
			log.append(",licensePlate=").append(licensePlate);
			log.append(",marketType=").append(marketType);
			log.append(",carOwner=").append(carOwner);
			log.append(",businessType=").append(businessType);
			log.append(",licensePlateCol=").append(licensePlateCol);
			log.append(",vin=").append(vin);
			log.append(",price=").append(price);
			log.append(",cyCardType=").append(cyCardType);
			log.append(",photo1=").append(photo1);
			log.append(",memberId=").append(memberId);
			log.append(",attnId=").append(attnId);
			log.append(",materialImages1=").append(materialImages1);
			log.append(",materialImages2=").append(materialImages2);
			log.append(",materialImages3=").append(materialImages3);
			log.append(",materialImages4=").append(materialImages4);
			log.append(",materialImages5=").append(materialImages5).append("]");

			LOGGER.info(log.toString());
			
			//信息内容要求：流水号、车辆库存类型、业务种类、车牌颜色、号牌种类必须有值
			if(StringUtil.isNullOrBlank(serial) )  {LOGGER.info("serial :"+serial +"流水号不能为空!"); return 2;	}
			if(marketType == null ) {  LOGGER.info("marketType :"+marketType +"车辆库存类型不能为空!"); return 2; }
			if(businessType == null ) { LOGGER.info("businessType :"+businessType +"业务种类不能为空!");return 2; }
			if(licensePlateCol == null ) {  LOGGER.info("licensePlateCol :"+licensePlateCol +"车牌颜色不能为空!"); return 2; }
			if(cyCardType == null) { LOGGER.info("cyCardType :"+cyCardType +"号牌种类不能为空!"); return 2;	}
			
			//
			String isAutoPay = Registry.getConfigFromDb("isAutoPay");
			int checkPrice = Integer.parseInt(Registry.getConfigFromDb("checkPrice"));
			int transferPrice = Integer.parseInt(Registry.getConfigFromDb("transferPrice"));
			if(isAutoPay.equalsIgnoreCase("on")){
				User user = User.getUserProfileByLoginid(attnId, null);
				if(user != null && user.getFlag() == 2) return 3;
				if(user != null && user.getFlag() == 3) return 4;
				MemberDao mDao = (MemberDao) TmsDao.getInstance(TmsDao.TMS_MEMBER);
				MemberDto member = mDao.findTransferDataSyn40000(memberId);
				if(member != null) {
					if(member.getRealMargin() == 0) return 5;
					if(businessType == 1 && member.getVirtualMargin() < (checkPrice+transferPrice)) return 6;
					if(businessType == 2 && member.getVirtualMargin() < checkPrice) return 6;
				}
			} else {
				return 1;
			}
			
			//
			TxController tx = TxController.getTxController();
			try {
				tx.begin();
				TransferProcessHistoryDao dao3 = (TransferProcessHistoryDao) TmsDao.getInstance(TmsDao.TMS_TRANSFER_PROCESS_HISTORY);
				TransferFinanceInfoDao dao2 = (TransferFinanceInfoDao) TmsDao.getInstance(TmsDao.TMS_TRANSFER_FINANCE_INFO);
				TransferAcceptedInfoDao dao = (TransferAcceptedInfoDao) TmsDao.getInstance(TmsDao.TMS_TRANSFER_ACCEPTED_INFO);	
				TransferAcceptedInfo Tai = TransferAcceptedInfo.getInstance();
				boolean isExistTransferSerial = Tai.findTransInfobySerial(serial);
				if(isExistTransferSerial) {
					TransferAcceptedInfoDto dto = new TransferAcceptedInfoDto();
					dto.setLicensePlateCol(String.valueOf(licensePlateCol));
					dto.setPrice(price);
					dto.setCardType(cyCardType);
					dto.setCarOwner(carOwner);
					dto.setPhoto_1(photo1);
					dto.setMaterialImages1(materialImages1);
					dto.setMaterialImages2(materialImages2);
					dto.setMaterialImages3(materialImages3);
					dto.setMaterialImages4(materialImages4);
					dto.setMaterialImages5(materialImages5);
					dto.setMemberId(memberId);
					dto.setAttnId(attnId);
					dto.setSerial(serial);
					dao.updateTransferDataSyn40000(dto);
				} else {
					TransferAcceptedInfoDto dto = new TransferAcceptedInfoDto();
					dto.setSerial(serial);
					dto.setLicensePlate(licensePlate);
					dto.setBasicCarId(basicCarId);
					dto.setMarketType(marketType);
					dto.setLicensePlateCol(String.valueOf(licensePlateCol));
					dto.setVin(vin);
					dto.setPrice(price);
					dto.setCarOwner(carOwner);
					dto.setCardType(cyCardType);
					dto.setPhoto_1(photo1);
					dto.setMaterialImages1(materialImages1);
					dto.setMaterialImages2(materialImages2);
					dto.setMaterialImages3(materialImages3);
					dto.setMaterialImages4(materialImages4);
					dto.setMaterialImages5(materialImages5);
					dto.setMemberId(memberId);
					dto.setCarClass(businessType==1 ? 2 : (businessType==2 ? 1 : null));
					dao.saveTransferDataSyn40000(dto);
					
					//
					TransferFinanceInfoDto dto2 = new TransferFinanceInfoDto();
					dto2.setSerial(serial);
					dao2.insertTransferFinanceInfo(dto2);
				}
				TransferProcessHistoryDto dto4 = new TransferProcessHistoryDto();
				dto4.setBusinessType(1);
				dto4.setSerial(serial);
				dto4.setInsertUserId(1);
				dao3.insertHisInfoAtAssess(dto4);
				
				//
				if(!StringUtil.isNullOrBlank(basicCarId)) {
					CarDao carDao = (CarDao) TmsDao.getInstance(TmsDao.TMS_CAR);
					MarketCarInfoDto marketCarInfoDto = carDao.findCarBySerial(basicCarId);
					if(marketCarInfoDto != null && marketCarInfoDto.getRegisterStatus() != 3 && marketCarInfoDto.getRegisterStatus() != 4) {
						marketCarInfoDto.setStatus(3);
						marketCarInfoDto.setSerial(basicCarId);
						marketCarInfoDto.setUpdateUserId(1);
						carDao.updateCarStatusOnly(marketCarInfoDto);
					}
				}
				
				//
				TransferAcceptedInfoDto dto1 = new TransferAcceptedInfoDto();
				dto1.setSerial(serial);
				dto1.setStatus(2);
				if(businessType == 1) dto1.setTransferPrice(transferPrice);
				dao.updateTransferDataSyn40000(dto1);
				
				//
				TransferFinanceInfoDto dto2 = new TransferFinanceInfoDto();
				dto2.setSerial(serial);
				dto2.setCheckPrice(checkPrice);
				dto2.setCheckPriceChargeType(3);
				if(businessType == 1) {
					dto2.setTransferPrice(transferPrice);
					dto2.setTransferPriceChargeType(3);
				}
				dto2.setBusinessType(businessType);
				dao2.updateTransferDataSyn40000(dto2);
				
				//
				TransferProcessHistoryDto dto3 = new TransferProcessHistoryDto();
				if(businessType == 1) {dto3.setBusinessType(8); dto3.setReason("手机申请过户，系统自动扣除");}
				else {dto3.setBusinessType(2); dto3.setReason("手机申请过户，系统自动扣除");}
				dto3.setSerial(serial);
				dto3.setInsertUserId(1);
				dao3.insertHisInfoAtAssess(dto3);
				tx.commit();
			} catch (Exception e) {
				LOGGER.error("transferDataSyn40000 error,", e);
				try {
					tx.rollback();
				} catch (TransactionException ex) {
					LOGGER.error("rollback error,", ex);
				}
			}
		} catch (Exception e) {
			LOGGER.error("TransferServiceImpl.transferDataSyn40000 error",e);
			r = 2;
		}
		return r;
	}

}
